import chart from '@/utils/chart.js' 
import { getDateList, toMMDD, toHHMM, formatTimeStamp } from '@/utils/timeUtil'
import { isNo, parseJson, transSceCount, formatKeyToCn } from '@/utils/tool'
import { COFFEE_TYPE, COFFEE_TYPE_LIMIT } from '@/consts/codeMaps'
import { ONE_DAY_MS } from '@/consts/consts'

function toStamp (t) {
  return new Date(t).getTime()
}

export const chartExtraction = (chartData, time_start, time_end, isOneDay, displayType) => {
  let fields = ['eTime']
  let coffeeData = chartData.filter(e => {
    const d = JSON.parse(JSON.parse(e.data))
    return Number(d.formula) === Number(displayType)
  })

  console.log('filed list>>>>>>>>', fields)
  console.log('displayType>>>>>>>>',displayType)
  console.log(coffeeData) 

  let series = []
  const upper = COFFEE_TYPE_LIMIT[displayType].u
  const lower = COFFEE_TYPE_LIMIT[displayType].l
  for (let i = 0; i < fields.length; i++) {
    const f = fields[i]

    let color = '#f1b85e'

    let o = {
      data: [],
      name: formatKeyToCn(f),
      ...chart.ECHART_LINE_CONFIG,
      symbolSize: 8,
      itemStyle: {
        color: color
      },
      lineStyle: {
        tye: 'solid',
        color: color,
        opacity: 0
      },
      markLine: {}
    }
    console.log("U L:", upper , lower)
    if (upper  && lower ) {
      console.log("U L: true")
      o.markLine = {
        symbol: 'none',
        silent: true,
        label: {
          show: true
        },
        data: [
          {
            yAxis: lower,
            lineStyle: {
              type: 'solid',
              color: '#ff0000',
              width: 1
            }
          },
          {
            yAxis: upper,
            lineStyle: {
              type: 'solid',
              color: '#ff0000',
              width: 1
            }
          }
        ]
      }
    }else {
      console.log("U L: false")
      o.markLine = {
        data: ''
      }
    }
    series.push(o)
    console.log('此时的series是：', series)
  }

  let objF1 = {
    data: [],
    type: 'line',
    name: '咖啡机水路压力',
    symbol: 'circle',
    sampling: 'average',
    showSymbol: false,
    showAllSymbol: false,
    yAxisIndex: 1,
    itemStyle: {
      color: '#515cc8'
    },
    lineStyle: {
      color: '#515cc8'
    }
  }
  // TODO
  // series.push(objF1)

  //
  if (coffeeData.length > 0) {
    for (let i = 0; i < coffeeData.length; i++) {
      let item = coffeeData[i]
      for (let j = 0; j < fields.length; j++) {
        // eTime
        const f = fields[j]
        for (let k = 0; k < series.length; k++) {
          const seriesItem = series[k]
          if (seriesItem.name === formatKeyToCn(f)) {
            const d = JSON.parse(JSON.parse(item.data))
            series[k].data.push([toStamp(item.create_time), d[f]])
          }
        }
      }
    }
  }

  /*
  if (this.chartData1.length > 0) {
    for (let i = 0; i < this.chartData1.length; i++) {
      let item = this.chartData1[i]
      objF1.data.push([item.upload, transSceCount(item.data.p4)]) // p4
    }
  } else {
    let xData = getDateList(time_start, time_end)
    for (let day of xData) {
      // 解决x轴最后2个重复问题
      objF1.data.push([day, 0])
    }
  }
  */
  console.log('>>>>>>>.series>>>>>>>>>>>', series)

  let xInterval = 1
  if (time_end - time_start >= 11 * 24 * 3600 * 1000) {
    xInterval = 4
  }

  let xAxisConfig = null 

  // 选择 一天 的x轴config
  if (isOneDay) {
    xAxisConfig = {
      splitLine: {
        show: false
      },
      type: 'time',
      maxInterval: 1 * 3600 * 1000,
      min: function (value) {
        let todayStart = new Date(
          new Date(value.min).toLocaleDateString()
        ).getTime()
        return todayStart
      },
      max: function (value) {
        let todayStart = new Date(
          new Date(value.min).toLocaleDateString()
        ).getTime()
        let todayEnd = todayStart + ONE_DAY_MS
        return todayEnd
      },
      axisLabel: {
        show: true,
        color: '#c3c6cd',
        rotate: 30,
        formatter: (value, index) => {
          let t = toHHMM(new Date(value).getTime())
          return `${t}`
        }
      }
      // data: xData
    }
  } else {
    // 选择 多天 的x轴config
    xAxisConfig = {
      splitLine: {
        show: false
      },
      type: 'time',
      maxInterval: 5 * 3600 * 24 * 1000,
      min: function (value) {
        let todayStart = new Date(
          new Date(value.min).toLocaleDateString()
        ).getTime()
        return todayStart
      },
      axisLabel: {
        show: true,
        color: '#c3c6cd',
        rotate: 0,
        boundaryGap: true,
        formatter: (value, index) => {
          let d = toMMDD(new Date(value).getTime())
          let t = toHHMM(new Date(value).getTime())
          return `${d} ${t}`
        }
      }
      // data: xData
    }
  }

  let option = {
    // color: ['#ffb400', 'green'],
    // grid: chart.DETAIL_GRID,
    grid: {
      top: '50',
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    // legend: chart.DETAIL_LEGEND,
    tooltip: {
      ...chart.TOOLTIP,
      formatter: (params, ticket) => {
        let s = ''
        // console.log('???????????', params, series)
        s = s + formatTimeStamp(params[0].axisValue) + `<br/>`

        for (let item of params) {
          let unit = item.seriesName === '咖啡机水路压力' ? 'PSI' : 's'
          s = s + `<span style="color:${item.color}">
                  <span class="tooltip-xl">${item.seriesName}: </span>${item.value[1]}${unit}</span></br>`
        }
        return s
      }
    }, 
    dataZoom: [
      {
        type: 'inside',
        throttle: 50
      }
    ],
    xAxis: {
      boundaryGap: true,
      ...xAxisConfig,
      nameTextStyle: {
        color: '#c3c6cd'
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#6E798B'
        }
      },
      axisTick:{
        show:false
      }
    },
    yAxis: [
      {
        name: 's       ',
        type: 'value',
        ...chart.AXIS_STYLE,
        max: function (value) {
          console.log('echarts图里的数据',value)
          if (value.max <= lower || (value.max <= upper && value.max >= lower)) {
            const maxnum = (upper + 5)/10
            return maxnum.toFixed(0) * 10
          } else {
            const maxnum = (value.max + 5)/10
            return Math.ceil(maxnum.toFixed(0) * 10)
          }
        }
      },
      {
        name: '',
        type: 'value',
        ...chart.AXIS_STYLE
      }
    ],

    series: series
  }
  return option
}